package com.corner.utils;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2015/5/9.
 */
public class DownLoadUtil {

    private static DownLoadUtil downLoadUtil;
    ExecutorService executorService;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj != null) {
                ((ProgressCallBack) msg.obj).hasFinish(msg.arg1, msg.arg2);
            }
        }
    };

    private DownLoadUtil() {
        executorService = Executors.newFixedThreadPool(5);
    }

    public static DownLoadUtil getInstance() {
        if (downLoadUtil == null) {
            downLoadUtil = new DownLoadUtil();
        }
        return downLoadUtil;
    }

    public void downLoad(File f, String url, final ProgressCallBack callBack) {
        /**
         *  最后从指定的url中下载图片
         */
        //from web
        try {
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            final int buffer_size = 1024;
            final int total = conn.getContentLength();
            int progress = 0;
            try {
                byte[] bytes = new byte[buffer_size];
                long lastTime = SystemClock.uptimeMillis();
                for (; ; ) {
                    int count = is.read(bytes, 0, buffer_size);
                    if (count == -1)
                        break;
                    os.write(bytes, 0, count);
                    if (callBack != null) {
                        progress += count;
                        long currTime = SystemClock.uptimeMillis();
                        if (currTime - lastTime > 1000) {
                            //UI线程更新太频繁会导致卡顿
                            lastTime = currTime;
                            Message message = handler.obtainMessage();
                            message.obj = callBack;
                            message.arg1 = progress;
                            message.arg2 = total;
                            handler.sendMessage(message);
                        }
                    }
                }
            } catch (Exception ex) {
            }
            os.close();
            conn.disconnect();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 下载文件
     *
     * @param path
     * @param url
     * @param callback
     */
    public void getFilePath(final String path, final String url, final GetFileCallBack callback, final ProgressCallBack progress) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    final File file = new File(path);
                    FileUtil.creatFile(path, FileUtil.FILE);
                    downLoad(file, url, progress);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFinish(file.getAbsolutePath());
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFinish(null);
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 下载文件
     *
     * @param path
     * @param url
     * @param callback
     */
    public void getFilePath(final String path, final String url, final GetFileCallBack callback) {
        getFilePath(path, url, callback, null);
    }

    public interface GetFileCallBack {
        void onFinish(String filePath);
    }

    public interface ProgressCallBack {
        void hasFinish(int progress, int total);
    }
}
